package com.xiliu.server.common.security.service;

import com.xiliu.server.common.security.entity.JwtUser;
import com.xiliu.server.modules.ucenter.entity.XlUser;
import com.xiliu.server.modules.ucenter.service.XlUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author xiliu
 * 会员用户认证服务
 * @date 2022/12/28 17:16
 */
@Service("memberUserDetailsService")
@RequiredArgsConstructor
public class MobileUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private XlUserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return null;
    }

    /**
     * openid 认证方式
     *
     * @param openId
     * @return
     */
    public UserDetails loadUserByOpenId(String openId) {
        JwtUser userDetails = null;
        XlUser result = userService.loadUserByOpenId(openId);

        if (result != null) {
            userDetails = new JwtUser(result.getUserId(),result,null);
        }
        if (userDetails == null) {
            throw new UsernameNotFoundException("用户不存在");
        } else if (!userDetails.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定!");
        } else if (!userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期!");
        }
        return userDetails;
    }
}
